# coding:UTF-8

import hashlib
import os
import json
import re
import time

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt

from controller.settings import BASE_DIR
from account.models import UserInfo as UserInfoDb
from controller.typechanging import NAME_TO_TYPE
from myblogs.models import BlogInfo as BlogInfoDb


# 站长主页
def index(request):
    if request.method == 'GET':
        obj = {"title": "我的主页"}
        if request.session.get('status') == 'login':
            obj['login'] = True
            obj['session'] = request.session
        else:
            obj['login'] = False

        blog_author_id = request.GET.get("user")
        if blog_author_id:
            blog_list = BlogInfoDb.objects.filter(blog_author_id=blog_author_id, status="True").order_by('-createTime')
            obj['bloglist'] = blog_list

            return render_to_response(
                "myblogs/index.html",
                {
                    'obj': obj,
                    'blog_author_id': blog_author_id
                },
                context_instance=RequestContext(request))


def user_info(request, author_id):
    # POST
    if request.method == "POST":
        try:
            user = UserInfoDb.objects.get(id=author_id)

            # print 'user_id:'+str(user_id)
            user.username = request.POST.get('user_name', None)
            # user.email=request.POST.get('user_email',None)
            user.tel_number = request.POST.get('user_phone', None)
            user.qq_number = request.POST.get('user_QQ', None)
            user.weibo_number = request.POST.get('user_weibo', None)
            user.introduction = request.POST.get('user_intro', None)
            user.save()
            return HttpResponseRedirect("/my_blog/user_info/"+ str(author_id) +"/?tip=revise")

        except UserInfoDb.DoesNotExist:
            # user = UserInfoDb()
            # user.user_id == str(UserInfoDb.objects.count() + 1)
            # user.save()
            return HttpResponseRedirect("/account/login/")

    # GET
    else:
        obj = {}
        obj['login'] = (request.session.get('status') == "login")
        try:
            user = UserInfoDb.objects.get(pk=author_id)
            obj['user'] = user
            obj['session'] = request.session
            obj["tip_for_save"] = (request.GET.get("tip") == "revise") and "已修改" or ""
        except UserInfoDb.DoesNotExist:
            return HttpResponse("无权进行此操作！")

        return render_to_response(
            "myblogs/user_info.html",
            {
                'obj': obj,
                'blog_author_id': author_id
            },
            context_instance=RequestContext(request)
        )


# 分块式上传
def handle_uploaded_file(f, absolute_path_filename):
    info = open(absolute_path_filename, 'wb+')
    for chunk in f.chunks():
        info.write(chunk)
    info.close()
    return info


# 上传并保存头像
def head_img_upload(request, author_id):
    # POST
    if request.method == "POST":
        email = request.session.get('email', None)
        login_token = request.session.get('login_token', None)
        if request.FILES.get('headimg'):
            path = BASE_DIR + '/static/upload/' + email
            if not os.path.exists(path):
                os.makedirs(path)
            absolute_path_filename = path + '/head_img.' + request.FILES['headimg'].name.split('.')[-1]
            handle_uploaded_file(request.FILES['headimg'], absolute_path_filename)
            try:
                user = UserInfoDb.objects.get(email=email, login_token=login_token)
                user.head_img_url = absolute_path_filename.replace(BASE_DIR, "")
                request.session['head_img_url'] = user.head_img_url
                user.save(update_fields=("head_img_url",))
                return HttpResponseRedirect("/my_blog/user_info/"+str(author_id))
            except UserInfoDb.DoesNotExist:
                return HttpResponse('还没有登录!')

        else:
            return HttpResponse('None choose any file!')

    # GET
    else:
        return render_to_response("producing.html", {})


@csrf_exempt
def ueditor_handler(request):
    if request.method == "GET":
        if request.GET.get("action", "") == "config":
            config_file_path = BASE_DIR + '/static/lib/plug/ueditor/php/config.json'
            config_file = open(config_file_path, 'r')
            try:
                json_string = config_file.read()
                re.sub("\/\*[\s\S]+?\*\/", "", json_string)
                config_file.close()
                return HttpResponse(json_string)
            except IOError:
                return HttpResponse("配置环境失败！")
    # POST
    else:
        return deal_upload_file(request)


# UEditor返回参数
def deal_upload_file(request):
    result = {
        "state": "SUCCESS",
        "url": "",
        "title": "",
        "original": "",
        "type": "image/gif",
        "size": "",
    }
    path = 'static/my_blog/pic/'
    path = path + time.strftime("%Y%m%d") + "/"
    linux_path = BASE_DIR + '/' + path
    print linux_path
    if not os.path.exists(linux_path):
        os.makedirs(linux_path)
    filename = hashlib.md5(str(time.time())).hexdigest()
    fp = request.FILES['upfile']
    fp_name = fp.name.encode("UTF-8")
    fp_name = fp_name.split(".")
    fp_name = filename + "." + fp_name[len(fp_name) - 1]
    result['size'] = fp.size
    result['original'] = fp_name
    result['url'] = "/" + path + fp_name
    save_fp = open(linux_path + fp_name, 'wb')
    save_fp.write(fp.read())
    save_fp.close()
    return HttpResponse(json.dumps(result))


def set_blog_pic_url(request, id):
    absolute_path_filename = BASE_DIR + '/static/file/blog'
    if not os.path.exists(absolute_path_filename):
        os.makedirs(absolute_path_filename)
    file_name_split = request.FILES['blog_pic'].name.split('.')
    absolute_path_filename = absolute_path_filename + '/blog_' + str(id) + '.' + file_name_split[
        len(file_name_split) - 1]
    handle_uploaded_file(request.FILES['blog_pic'], absolute_path_filename)
    return absolute_path_filename.replace(BASE_DIR, "")


def add_blog(request):
    obj = {}

    if request.method == 'GET':
        # 站长访问
        if request.session.get("email"):
            type_dict = NAME_TO_TYPE.values()
            obj["type_dict"] = type_dict
            obj['login'] = True
            obj['session'] = request.session

            return render_to_response(
                "myblogs/addblog.html",
                {
                    'obj':
                        {
                            "type_dict": type_dict,
                            "login": True,
                            "session": request.session
                        }
                },
                context_instance=RequestContext(request))
        else:
            # 普通用户访问
            return render_to_response(
                "myblogs/sendblogs.html",
                {
                    'obj': obj
                },
                context_instance=RequestContext(request))
    # POST
    else:
        blog_title = request.POST.get("blog_title", '')
        blog_tags = request.POST.get("blog_tags_select", '其他')
        blog_preview = request.POST.get("blog_preview", '')
        blog_content = request.POST.get("blog_content", '')

        user_id = request.session.get("user_id", 0)
        try:
            user = UserInfoDb.objects.get(id=user_id)
        except UserInfoDb.DoesNotExist:
            return HttpResponse("你不是管理员!")

        blog = BlogInfoDb(
            blog_author=user,
            blog_title=blog_title,
            blog_preview=blog_preview,
            blog_tags=blog_tags,
            blog_content=blog_content,
        )
        blog.save()
        # 设置上传文件的路径
        blog.blog_pic_url = request.FILES.get('blog_pic', None) and set_blog_pic_url(request, blog.id) or ""
        blog.save(update_fields=("blog_pic_url",))
        return HttpResponseRedirect('/my_blog/?user='+str(user_id))


def rewrite_blog(request, blog_id):
    # POST
    if request.method == "POST":
        blog_title = request.POST.get("blog_title", '')
        blog_tags = request.POST.get("blog_tags_select", '其他')
        blog_preview = request.POST.get("blog_preview", '')
        user_id = request.session.get("user_id", 0)

        try:
            user = UserInfoDb.objects.get(id=user_id, status="True")
            blog_content = request.POST.get("blog_content", '')
            blog = BlogInfoDb.objects.get(id=blog_id, status="True")
            blog.blog_author = user
            blog_pic_url = request.FILES.get('blog_pic', None) and set_blog_pic_url(request,
                                                                                    blog.id) or blog.blog_pic_url
            blog.blog_pic_url = blog_pic_url
            blog.blog_title = blog_title
            blog.blog_preview = blog_preview
            blog.blog_content = blog_content
            blog.save()
            return HttpResponseRedirect('/account/backstage/')
        except (UserInfoDb.DoesNotExist, BlogInfoDb.DoesNotExist):
            return HttpResponse("非管理员操作，修改不成功！")

    else:
        return HttpResponse("该请求无效！")
